<template>
  <div class="min-h-screen bg-blue-50 p-4 sm:p-6 md:p-8">
    <showMessage ref="showMessageRef" />
    <div class="w-4/5 mx-auto">
      <h1 class="text-3xl font-bold text-blue-600 mb-6">思维导图</h1>
      
      <!-- 初始状态 - 未生成思维导图 -->
      <div v-if="!mindMapStore.mindMapGenerated" class="bg-white rounded-lg shadow-md p-6 text-center">
        <div class="mb-4">
          <svg class="w-24 h-24 mx-auto text-blue-300" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 13h6m-3-3v6m5 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
          </svg>
        </div>
        <p class="text-gray-600 mb-4">您还未生成思维导图，请先阅读当前文档后点击生成</p>
        <button
          @click="generateMindMap"
          :disabled="mindMapStore.isLoading"
          class="bg-blue-500 hover:bg-blue-600 text-white font-semibold py-2 px-4 rounded focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50 transition duration-150 ease-in-out"
          :class="{ 'opacity-50 cursor-not-allowed': mindMapStore.isLoading }"
        >
          <span v-if="!mindMapStore.isLoading">生成思维导图</span>
          <span v-else class="flex items-center">
            <svg class="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
              <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
              <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            生成中...
          </span>
        </button>
      </div>

      <!-- 已生成状态 -->
      <div v-else class="bg-white rounded-lg shadow-md p-6">
        <!-- 创建一个包含菜单栏和思维导图的容器，作为全屏目标 -->
        <div ref="fullscreenContainer" class="w-full bg-white">
          <!-- 添加功能菜单栏 -->
          <div class="mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200">
            <div class="flex flex-wrap gap-3">
              <div class="flex items-center">
                <span class="text-sm font-medium text-gray-700 mr-2">主题：</span>
                <select 
                  v-model="selectedTheme" 
                  @change="changeTheme"
                  class="text-sm border border-gray-300 rounded-md px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500"
                >
                  <option value="primary">默认蓝色</option>
                  <option value="success">绿色</option>
                  <option value="warning">黄色</option>
                  <option value="danger">红色</option>
                  <option value="info">浅蓝色</option>
                  <option value="greensea">绿海</option>
                </select>
              </div>
              
              <div class="border-l border-gray-300 h-6 mx-1"></div>
              
              <div class="flex items-center space-x-2">
                <span class="text-sm font-medium text-gray-700">缩放：</span>
                <button 
                  @click="zoomIn"
                  class="text-sm bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium py-1 px-2 rounded"
                >
                  放大
                </button>
                <button 
                  @click="zoomOut"
                  class="text-sm bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium py-1 px-2 rounded"
                >
                  缩小
                </button>
              </div>
              
              <div class="border-l border-gray-300 h-6 mx-1"></div>
              
              <div class="flex items-center space-x-2">
                <span class="text-sm font-medium text-gray-700">节点：</span>
                <button 
                  @click="expandAll"
                  class="text-sm bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium py-1 px-2 rounded"
                >
                  全部展开
                </button>
                <button 
                  @click="collapseAll"
                  class="text-sm bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium py-1 px-2 rounded"
                >
                  全部折叠
                </button>
              </div>
              
              <div class="border-l border-gray-300 h-6 mx-1"></div>
              
              <div class="flex items-center space-x-2">
                <span class="text-sm font-medium text-gray-700">导出：</span>
                <button 
                  @click="downloadJM"
                  class="text-sm bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium py-1 px-2 rounded"
                >
                  下载文件
                </button>
                <button 
                  @click="takeScreenshot"
                  class="text-sm bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium py-1 px-2 rounded"
                >
                  截图
                </button>
              </div>
              
              <div class="border-l border-gray-300 h-6 mx-1"></div>
              
              <div class="flex items-center space-x-2">
                <button 
                  @click="toggleFullscreen"
                  class="text-sm bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium py-1 px-2 rounded flex items-center"
                >
                  <svg v-if="!isFullscreen" class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5v-4m0 4h-4m4 0l-5-5"></path>
                  </svg>
                  <svg v-else class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                  </svg>
                  {{ isFullscreen ? '退出全屏' : '全屏显示' }}
                </button>
              </div>
              
              <!-- 新增保存按钮 -->
              <div class="border-l border-gray-300 h-6 mx-1"></div>
              
              <div class="flex items-center space-x-2">
                <button 
                  @click="saveMindMap"
                  class="text-sm font-medium py-1 px-2 rounded flex items-center"
                  :class="isModified ? 'bg-red-500 hover:bg-red-600 text-white' : 'bg-gray-100 hover:bg-gray-200 text-gray-700'"
                >
                  保存
                </button>
              </div>
            </div>
          </div>
          
          <div 
            ref="mindMapContainer" 
            :class="[
              'w-full overflow-auto border border-gray-200 rounded mb-4',
              isFullscreen ? 'h-[calc(100vh-120px)]' : 'h-[500px]'
            ]"
          ></div>
        </div>
        
        <!-- 修改这里：显示新增页码数据 -->
        <div v-if="mindMapStore.hasNewRecords" class="mb-4">
          <div class="text-blue-600 font-semibold mb-2">新增的阅读记录：</div>
          <div class="flex flex-wrap gap-2">
            <span 
              v-for="page in mindMapStore.pageNumbers" 
              :key="page" 
              class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-blue-100 text-blue-800 border border-blue-200"
            >
              第 {{ page }} 页
            </span>
          </div>
          <div class="mt-2 text-blue-600">点击下方按钮更新思维导图</div>
        </div>
        
        <div v-else class="text-gray-600 mb-4">
          暂无新的阅读记录
        </div>
        <button 
          @click="updateMindMap"
          :disabled="mindMapStore.isLoading || !mindMapStore.hasNewRecords"
          class="bg-blue-500 hover:bg-blue-600 text-white font-semibold py-2 px-4 rounded focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50 transition duration-150 ease-in-out"
          :class="{ 'opacity-50 cursor-not-allowed': mindMapStore.isLoading || !mindMapStore.hasNewRecords }"
        >
          <span v-if="!mindMapStore.isLoading">更新思维导图</span>
          <span v-else class="flex items-center">
            <svg class="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
              <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
              <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            更新中...
          </span>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, onBeforeUnmount } from 'vue';
// @ts-ignore
import jsMind from 'jsmind';
import 'jsmind/style/jsmind.css';
import 'jsmind/screenshot';
import 'jsmind/draggable-node';
import { useMindMapStore } from '@/stores/mindMap';
import { useGeneralStore } from '@/stores/general';
import showMessage from '@/components/share/showMessage.vue';
import { generate_node_id } from '@/utils/utils';


const mindMapStore = useMindMapStore();
const generalStore = useGeneralStore();
const mindMapContainer = ref(null);
const fullscreenContainer = ref(null);
const showMessageRef = ref(null);
const selectedTheme = ref('primary'); // 默认主题
const isFullscreen = ref(false);
const isModified = ref(false); // 新增：跟踪思维导图是否已修改


let jm = null;

// 在组件挂载时初始化
onMounted(async () => {
  // 获取当前材料的思维导图
  if ( !generalStore.getMaterialId()) {
    showMessageRef.value.showMessage('请先选择材料', 'BUG');
    return;
  }
  const hasMindMap = await mindMapStore.getMindMap();
  
  // 如果有思维导图数据，渲染思维导图
  if (hasMindMap) {
    nextTick(() => {
      renderMindMap();
    });
  }
  
  // 检查是否有新记录
  await mindMapStore.checkNewRecords();
  
  // 添加全屏变化事件监听
  document.addEventListener('fullscreenchange', handleFullscreenChange);
  // @ts-ignore: 浏览器特定API
  document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
  // @ts-ignore: 浏览器特定API
  document.addEventListener('mozfullscreenchange', handleFullscreenChange);
  // @ts-ignore: 浏览器特定API
  document.addEventListener('MSFullscreenChange', handleFullscreenChange);
  
  // 初始化快捷键处理
  document.addEventListener('keydown', handleKeyDown);
});


// 监听思维导图数据变化
watch(() => mindMapStore.mindMapData, (newVal) => {
  if (newVal) {
    nextTick(() => {
      renderMindMap();
    });
  }
});

// 生成思维导图
async function generateMindMap() {
  const success = await mindMapStore.generateMindMap();
  if (success) {
    nextTick(() => {
      renderMindMap();
    });
  }
}

// 更新思维导图
async function updateMindMap() {
  const success = await mindMapStore.updateMindMap();
  if (success) {
    nextTick(() => {
      renderMindMap();
    });
  }
}

// 缩放功能
function zoomIn() {
  if (jm) {
    jm.view.zoomIn();
  }
}

function zoomOut() {
  if (jm) {
    jm.view.zoomOut();
  }
}

// 展开/折叠功能
function expandAll() {
  if (jm) {
    jm.expand_all();
  }
}

function collapseAll() {
  if (jm) {
    jm.collapse_all();
  }
}

// 切换主题
function changeTheme() {
  if (jm) {
    renderMindMap();
  }
}

// 渲染思维导图
function renderMindMap() {
  if (!mindMapContainer.value || !mindMapStore.mindMapData) {
    showMessageRef.value?.showMessage('思维导图容器或数据不存在', 'error');
    return;
  }

  // 初始化 jsMind 实例（仅首次）
  if (!jm) {
    jm = new jsMind({
      container: mindMapContainer.value,
      theme: selectedTheme.value, // 使用选择的主题
      editable: true,
      view: {
        engine: 'canvas',
        hmargin: 100,
        vmargin: 50,
        line_width: 2,
        line_color: '#2563eb',
        draggable: true, // 是否允许拖动画布
        hide_scrollbars_when_draggable: false, // 当 draggable 为 true 时是否隐藏滚动条
      },
      shortcut: {
        enable: false,  // 启用快捷键
        handles: {}, 
        mapping: {
          addchild: [45, 4096 + 13],  // Insert键, Ctrl+Enter
          addbrother: 13,             // Enter键
          editnode: 113,              // F2键
          delnode: 46,                // Delete键
          toggle: 32,                 // 空格键
          left: 37,                   // 左箭头
          up: 38,                     // 上箭头
          right: 39,                  // 右箭头
          down: 40,                   // 下箭头
        }
      }
    });
  
  } else {
    // 更新主题
    jm.set_theme(selectedTheme.value);
  }
  
  // 显示数据
  jm.show(mindMapStore.mindMapData);

  // 重置修改状态
  isModified.value = false;
}


// 下载 .jm 文件
function downloadJM() {
  if (!jm) return;
  
  try {
    const data = jm.get_data();
    const jsonData = JSON.stringify(data);
    const blob = new Blob([jsonData], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    
    const a = document.createElement('a');
    a.href = url;
    a.download = `思维导图_${new Date().toISOString().slice(0, 10)}.jm`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    showMessageRef.value.showMessage('文件下载成功', 'success');
  } catch (error) {
    console.error('下载文件失败', error);
    showMessageRef.value.showMessage('下载文件失败', 'error');
  }
}

// 截图功能
function takeScreenshot() {
  if (!jm) return;
  
  try {
    jm.shoot()
    showMessageRef.value.showMessage('截图已下载', 'success');
  } catch (error) {
    console.error('截图失败', error);
    showMessageRef.value.showMessage('截图失败', 'error');
  }
}

// 全屏切换功能
function toggleFullscreen() {
  if (!fullscreenContainer.value) return;
  
  if (!isFullscreen.value) {
    // 进入全屏
    if (fullscreenContainer.value.requestFullscreen) {
      fullscreenContainer.value.requestFullscreen();
    } else if (fullscreenContainer.value.webkitRequestFullscreen) { /* Safari */
      // @ts-ignore: 浏览器特定API
      fullscreenContainer.value.webkitRequestFullscreen();
    } else if (fullscreenContainer.value.msRequestFullscreen) { /* IE11 */
      // @ts-ignore: 浏览器特定API
      fullscreenContainer.value.msRequestFullscreen();
    }
  } else {
    // 退出全屏
    if (document.exitFullscreen) {
      document.exitFullscreen();
      // @ts-ignore: 浏览器特定API
    } else if (document.webkitExitFullscreen) { /* Safari */
      // @ts-ignore: 浏览器特定API
      document.webkitExitFullscreen();
      // @ts-ignore: 浏览器特定API
    } else if (document.msExitFullscreen) { /* IE11 */
      // @ts-ignore: 浏览器特定API
      document.msExitFullscreen();
    }
  }
}

// 监听全屏状态变化
function handleFullscreenChange() {
  isFullscreen.value = !!document.fullscreenElement;
}

// 处理快捷键
function handleKeyDown(e) {
  if (!jm) return;
  
    // 修改：在关键操作前记录历史
    const recordHistory = () => {
    const currentData = jm.get_data();
    mindMapStore.addHistory(currentData);
    isModified.value = true;
    }
  
  // Ctrl+alt+S: 保存思维导图
  if (e.key === 's' && (e.ctrlKey || e.metaKey) && e.altKey) {
    e.preventDefault();
    saveMindMap();
    return;
  }
  
  // Ctrl+Z: 撤销操作
  if (e.key === 'z' && (e.ctrlKey || e.metaKey)) {
    e.preventDefault();
    undoLastChange();
    return;
  }
  
  // 获取当前选中的节点
  const selected_node = jm.get_selected_node();
  if (!selected_node) return;
  let parent_node = selected_node.parent;

  // Enter 键：添加同级节点
  if (e.key === 'Enter' && !e.ctrlKey) {
    e.preventDefault();
    console.log("Enter 记录了历史记录")
    recordHistory();
    jm.add_node(parent_node,generate_node_id(),"新节点")
  }
  
  // Ctrl+Enter 键：添加子节点
  if (e.key === 'Enter' && e.ctrlKey) {
    e.preventDefault();
    console.log("Ctrl+Enter 记录了历史记录")
    recordHistory();
    jm.add_node(selected_node,generate_node_id(),"新节点")
  }
  
  // Delete 键：删除节点
  if (e.key === 'Delete') {
    e.preventDefault();
    console.log("Delete 记录了历史记录")
    recordHistory();
    jm.remove_node(selected_node)
  }
}

// 新增：撤销上一步操作
function undoLastChange() {
  if (!jm) return;
  
  const previousData = mindMapStore.undoLastChange();
  console.log("previousData:",previousData)
  if (previousData) {
    jm.show(previousData);
    isModified.value = true;
    showMessageRef.value.showMessage('已撤销上一步操作', 'info');
  } else {
    showMessageRef.value.showMessage('没有可撤销的操作', 'info');
  }
}

// 新增保存思维导图功能
async function saveMindMap() {
  if (!jm || !isModified.value) return;
  
  try {
    const data = jm.get_data();
    await mindMapStore.saveMindMapData(data);
    isModified.value = false;
    mindMapStore.resetHistory();
    showMessageRef.value.showMessage('思维导图保存成功', 'success');
  } catch (error) {
    console.error('保存思维导图失败', error);
    showMessageRef.value.showMessage('保存思维导图失败', 'error');
  }
}

// 组件卸载时清理事件监听
onBeforeUnmount(() => {
  // 组件卸载前移除事件监听
  document.removeEventListener('fullscreenchange', handleFullscreenChange);
  // @ts-ignore: 浏览器特定API
  document.removeEventListener('webkitfullscreenchange', handleFullscreenChange);
  // @ts-ignore: 浏览器特定API
  document.removeEventListener('mozfullscreenchange', handleFullscreenChange);
  // @ts-ignore: 浏览器特定API
  document.removeEventListener('MSFullscreenChange', handleFullscreenChange);
  
  // 移除键盘事件监听
  document.removeEventListener('keydown', handleKeyDown);
});
</script>